package com.onion.mvc.resolver.exception;

import com.alibaba.fastjson.JSON;
import com.onion.utils.support.exception.OnionException;
import com.onion.utils.surface.response.ResultHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MvcExceptionHandler implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(MvcExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                         Object param, Exception exp) {
        if(exp instanceof OnionException){
            logger.error("系统处理异常:errno={}, errmsg={}", ((OnionException) exp).getErrno(), exp.getMessage());
            this.writeMessage(response, JSON.toJSONString(ResultHelper.failure(((OnionException) exp).getErrno(), exp.getMessage())));
        }else{
            logger.error("Uncapped exception!", exp);
            this.writeMessage(response, JSON.toJSONString(ResultHelper.failure(-999, "Uncapped exception!")));
        }
        return null;
    }

    private void writeMessage(HttpServletResponse response, String errmsg){
        PrintWriter writer = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            writer = response.getWriter();
            writer.write(errmsg);
        } catch (IOException e) {
        } finally {
            if(writer != null){
                writer.flush();
                writer.close();
            }
        }
    }

}